<?php
  /**
  * Management of subjects in PrayOnline
  * @author: trungdt
  * @since: Jan 21, 2011
  * @version: 1.0
  * 
  * 
  * Database structure
  * CREATE  TABLE IF NOT EXISTS `po_subjects` (
    `name` TEXT NULL ,
   `add_date` INT(11) NULL ,
   `id` INT NOT NULL AUTO_INCREMENT , PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci
   
  * Change logs
  * Jan 21, 2011 - trungdt - First create
  */
  if (!defined('EXPONENT')) exit('');
  
  /**
  * How many items per page
  * WARNING: Must implement better in module config
  */
  $max_item =15;
    
  $lang=exponent_lang_loadFile("modules/praymodule/actions/subject_management.php");
  // Administrator access restrict
  if (exponent_users_isAdmin() || exponent_permissions_check('view_subjects',$loc))
  {
    // set flow
    exponent_flow_set(SYS_FLOW_PROTECTED,SYS_FLOW_ACTION);
    
    // pagination
    // we count all post
    $count_post = $db->countObjects('subjects');

    // page split
    // cal how many posts
    $pages=floor($count_post / $max_item);
    if ($count_post % $max_item != 0)
        $pages++;

    // get page
    $page=1;
    if (isset($_REQUEST['page']))  $page=intval($_REQUEST['page']);
    if (($page<1) || ($page>$pages)) $page=1;
    $start_pos=($page-1)*$max_item;
    // end of pagination
    
    // now we dont need location_data to store all info, we query db
    $data=$db->selectObjects("subjects"," 1 ORDER BY add_date DESC LIMIT {$start_pos},{$max_item}");
    
    foreach ($data as $key=>$value)
    {
        //$value->add_date=date(DISPLAY_DATETIME_FORMAT,$data->add_date);
        $pastors=$db->selectObjectsBySql("
            SELECT {$db->prefix}pastors.* 
            FROM 
            ({$db->prefix}pastors INNER JOIN {$db->prefix}pastor_subject 
                ON {$db->prefix}pastor_subject.pastor_id = {$db->prefix}pastors.id)
            INNER JOIN {$db->prefix}subjects 
            ON {$db->prefix}subjects.id = {$db->prefix}pastor_subject.subject_id
            WHERE {$db->prefix}subjects.id={$value->id}");
        
        $value->pastors=$pastors;
    }
    $template=new template("praymodule","_subject_management");
    $template->assign("data",$data);
    $template->register_permissions(array('view_subjects',"administrate"),$loc);  
    $template->assign("page",$page);
    $template->assign("pages",$pages);
    $template->assign("start_index",$start_pos); 
    $template->output();
  }
  else
  {
      echo SITE_403_HTML;
  }
?>
